package com.sd.repay.sms;

import com.sd.repay.pojo.SmsConfig;
import com.sd.repay.pojo.SmsInfo;
import com.sd.repay.utils.WebUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;


/**
 * 短信路由
 *
 * @author LA
 */
@Service
public class SmsRouteService {

    private static final Logger log = LoggerFactory.getLogger(SmsRouteService.class);
    @Resource
    private SmsDb smsDb;

    private static final int minute = 3;
    private final String perfix = "【 闪动金管家】";
    private Map<String, Object> smsChannel = new HashMap<String, Object>();
    @Resource
    private GKGSmsService gkgSmsService;


    private void initChannel() {
        //短信渠道初始化  实例：smsChannel.put("testService", testService);
        //key 名称对应短信路由表中配置的名称，value 对应配置的Service
        smsChannel.put("gkgSmsService", gkgSmsService);
    }

    /**
     * 路由规则
     *
     * @param smsInfo
     * @return
     */
    public BaseSmsService smsSendRoute(SmsInfo smsInfo) {
        String channel = smsInfo.getSms_business();
        BaseSmsService baseSmsService = null;
        Map<String, Object> smsChannelMap = smsDb.getSmsRouteByBusinessCode(channel);
        if (smsChannelMap == null || smsChannelMap.isEmpty()) {
            smsChannelMap = smsDb.getSmsRouteByBusinessCode("default");
        }

        if (smsChannelMap != null && !smsChannelMap.isEmpty()) {
            if (smsChannel.isEmpty()) {
                initChannel();
            }

            try {
                Object serviceName = smsChannel.get(smsChannelMap.get("service_code").toString());
                baseSmsService = (BaseSmsService) serviceName;
            } catch (Exception e) {
                log.error("手机号[{}]短信发送失败,短信路由信息[{}]转换错误：{}", new Object[]{smsInfo.getMobiles(), smsChannelMap.toString(), e});
                return baseSmsService;
            }
        }

        return baseSmsService;
    }

    /**
     * 发送短信
     *
     * @param smsInfo 短信实体对象
     */
    public void smsSend(SmsInfo smsInfo) {
        boolean isWhiteList = false;

        /**
         * 黑/白名单校验-白名单不受当天条数限制
         */
        Map<String, Object> riskMap = smsDb.getSmsRisk(smsInfo.getMobiles());
        if (riskMap != null && !riskMap.isEmpty()) {
            String risk_type = riskMap.get("risk_type").toString();
            if ("1".equals(risk_type)) {
                log.info("手机号[{}]已列入短信白名单：{}", smsInfo.getMobiles(), riskMap.toString());
                isWhiteList = true;
            } else {
                log.info("手机号[{}]短信发送失败,该手机号已被列入黑名单：{}", smsInfo.getMobiles(), riskMap.toString());
                smsInfo.setSms_status("1");
                smsInfo.setSms_rsp_msg("短信发送失败,该手机号存在风险。");
                return;
            }
        }

        /**
         * 当日短信次数校验,白名单用户不校验
         */
        String smsSendCount = WebUtil.getSysValue("SMS_SEND_COUNT");
        if (!StringUtils.isBlank(smsSendCount) && !isWhiteList) {
            int restrict_count = Integer.parseInt(smsSendCount);
            long todaySendCount = smsDb.getSmsCount(smsInfo.getMobiles());
            if (todaySendCount >= restrict_count) {
                log.info("手机号[{}]短信发送失败,当天短信发送条数已达上限[{}]", smsInfo.getMobiles(), todaySendCount);
                smsInfo.setSms_status("1");
                smsInfo.setSms_rsp_msg("短信发送失败,当天短信发送条数已达上限。");
                return;
            }
        }

        /**
         * 重置未校验验证码状态
         */
        if ("1".equals(smsInfo.getSms_type())) {
            long noCheckCount = smsDb.getNoCheckCodeCount(smsInfo.getMobiles(), smsInfo.getSms_business());
            if (noCheckCount > 0) {
                int count = smsDb.flushSmsCheckCode(smsInfo.getMobiles(), smsInfo.getSms_business());
                log.info("手机号[{}]短信验证码重发,查询到[{}]条验证码未校验，系统成功处理[{}]条验证码为废弃状态", smsInfo.getMobiles(), noCheckCount, count);
            }
        }

        /**
         * 获取通道路由
         */
        BaseSmsService baseSmsService = smsSendRoute(smsInfo);
        if (baseSmsService == null) {
            log.info("手机号[{}]短信发送失败,未获取到短信路由[{}]", smsInfo.getMobiles(), smsInfo.getSms_business());
            smsInfo.setSms_status("1");
            smsInfo.setSms_rsp_msg("短信发送失败, 未找到可用路由。");
            return;
        }


        Map<String, Object> configMap = smsDb.getSmsChannelInfo(baseSmsService.getChannel());
        if (configMap == null || configMap.isEmpty()) {
            log.info("手机号[{}]短信发送失败,无可用短信通道。", smsInfo.getMobiles());
            smsInfo.setSms_status("1");
            smsInfo.setSms_rsp_msg("短信发送失败,无可用短信通道。");
            return;
        }

        SmsConfig smsConfig = new SmsConfig();
        smsConfig.setId(Integer.parseInt(configMap.get("id").toString()));
        smsConfig.setSms_platform_name((String) configMap.get("sms_platform_name"));
        smsConfig.setSms_platform_code((String) configMap.get("sms_platform_code"));
        smsConfig.setPlatform_user_name((String) configMap.get("platform_user_name"));
        smsConfig.setPlatform_pwd((String) configMap.get("platform_pwd"));
        smsConfig.setPlatform_url((String) configMap.get("platform_url"));
        smsConfig.setCreate_time((Timestamp) configMap.get("create_time"));
        smsConfig.setCreate_person((String) configMap.get("create_person"));
        smsInfo.setSms_channel(smsConfig.getSms_platform_code());
        smsInfo.setSms_user_name(smsConfig.getPlatform_user_name());
        smsPrefix(smsInfo); //短信模板
        if (!StringUtils.isBlank(smsInfo.getSms_status()) && "1".equals(smsInfo.getSms_status())) {
            log.info("手机号[{}]发送短信失败,未找到短信模板[{}]", smsInfo.getMobiles(), "SMS_PREFIX" + smsInfo.getSms_type());
            return;
        }
        smsInfo.setSms_status("1"); //未提交
        smsInfo.setVali_status("1");//未校验
        long smsId = 0L;
        try {
            smsInfo.setSms_content(perfix.concat(smsInfo.getSms_content()));
            smsId = smsDb.initSms(smsInfo);
        } catch (Exception e) {
            log.error("手机号[{}]短信发送失败,初始化短信失败，系统出现未知异常:{}", smsInfo.getMobiles(), e);
            smsInfo.setSms_status("1");
            smsInfo.setSms_rsp_msg("发送失败,初始化短信失败");
            return;
        }
        smsInfo.setId(smsId);
        log.info("手机号[{}]短信发送[{}]通道[{}]", smsInfo.getMobiles(), smsInfo.getSms_content(), smsConfig.getSms_platform_name());
       //smsSuffix(smsInfo); //短信后缀
        baseSmsService.smsSend(smsInfo, smsConfig);

		
		/*if(smsConfig.getSms_platform_code().equalsIgnoreCase("umpp")){
            umfintechSms.getOrderNo(smsInfo);
			smsSuffix(smsInfo); //短信后缀
			umfintechSms.smsSend(smsInfo, smsConfig);
		}else{
			log.info("手机号[{}]短信发送失败,未知的短信通道[{}]", smsInfo.getMobiles(), smsConfig.getSms_platform_code());
			smsInfo.setSms_status("1");
			smsInfo.setSms_rsp_msg("发送失败,未找到可用的短信通道");
		}*/


    }

    /**
     * 短信通知
     *
     * @param message 通知内容
     */
    public void message(String message) {

    }

    /**
     * 验证码校验
     *
     * @param smsInfo
     */
    public void checkValidateCode(SmsInfo smsInfo) {
        int count = smsDb.valiCode(smsInfo, minute);
        if (count > 0) {
            smsInfo.setVali_status("2");
            smsInfo.setSms_rsp_msg("校验成功!");
            return;
        }
        smsInfo.setVali_status("1");
        smsInfo.setSms_rsp_msg("校验失败!");
    }

    /**
     * 随机生成6位数验证码
     *
     * @return
     */
    private String verificationCode() {
        Random random = new Random();
        int x = random.nextInt(899999);
        int x2 = x + 100000;
        return String.valueOf(x2);
    }

    /**
     * 短信模板
     *
     * @param smsInfo
     */
    private void smsPrefix(SmsInfo smsInfo) {
        if ("0".equals(smsInfo.getSms_type())) { //原始短信-带有后缀
            return;
        } else if ("1".equals(smsInfo.getSms_type())) { //sms_type=1固定短信验证码模板
            String valiCode = verificationCode();
            smsInfo.setSms_content(String.format(WebUtil.getSysValue("SMS_PREFIX" + smsInfo.getSms_type()), valiCode));
            smsInfo.setVali_code(valiCode);
            return;
        } else {
            //自定义模板
            String templateConfig = WebUtil.getSysValue("SMS_PREFIX" + smsInfo.getSms_type());
            if (StringUtils.isBlank(templateConfig)) {
                smsInfo.setSms_status("1");
                smsInfo.setSms_rsp_msg("发送失败,未找到可用的短信模板");
                return;
            }
            String[] templateArrayStr = templateConfig.split("%s");
            //String[] smsContentArrayStr = smsInfo.getSms_content().split("&");
            String[] smsContentArrayStr = smsInfo.getSms_content().split(",");
            if (templateArrayStr.length != smsContentArrayStr.length) {
                smsInfo.setSms_status("1");
                smsInfo.setSms_rsp_msg("发送失败,短信模板与模板参数数量不匹配");
                return;
            }
            String template = String.format(templateConfig, smsContentArrayStr);
            smsInfo.setSms_content(template);
        }
    }


    /**
     * 短信后缀-所有短信都将带此后缀，后缀不存入发送记录表中
     *
     * @param smsInfo
     */
    private void smsSuffix(SmsInfo smsInfo) {
        smsInfo.setSms_content(smsInfo.getSms_content().concat(String.format(WebUtil.getSysValue("SMS_SUFFIX"), smsInfo.getId())));
    }

}
